package com.zsc.edu.testfragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class ChatFragment extends Fragment {

    private RecyclerView recyclerView;
    private ChatAdapter chatAdapter;
    private List<ChatMessage> chatMessages;

    @Nullable
    @Override
    public View onCreateView(@NonNull  LayoutInflater inflater,
                             @Nullable  ViewGroup container,
                             @Nullable  Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);

        //  根据 chat_fragment 布局的id,  将其 inflate 出来
        View view = inflater.inflate(R.layout.chat_fragment, container, false);

        // recyclerView
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        // 初始化数据
        chatMessages = new ArrayList<>();

        //设置适配器
        chatAdapter = new ChatAdapter(chatMessages);
        recyclerView.setAdapter(chatAdapter);


        // 获得 EditText 的消息，这是发送者的消息
        EditText et = view.findViewById(R.id.edit_text);

        view.findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String send_msg = et.getText().toString();
                // 增加一个发送者消息
                chatMessages.add(new ChatMessage(send_msg,  true));
                // 通知适配器改变UI
                chatAdapter.notifyItemInserted(chatMessages.size()-1);

                // 增加一个接收者消息，内容任意
//                String receive_msg = "Hello, I am here!";
//                chatMessages.add(new ChatMessage(receive_msg, false));
//                // 通知适配器改变UI
//                chatAdapter.notifyItemInserted(chatMessages.size()-1);

                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            // 新建URL对象
                            URL url = new URL("http://192.168.31.89:8080/v1/engines/gpt2_117M/chat");

                            // 打开连接，并且强转为HttpURLConnection
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                            // 设置请求头
                            conn.setRequestProperty("Content-Type", "application/json; utf-8");
                            conn.setRequestProperty("Accept", "application/json");

                            // 设置请求方法为 POST
                            conn.setRequestMethod("POST");

                            // 允许输出
                            conn.setDoOutput(true);

                            // 构建POST的JSON 数据
                            String jsonInputString = "{\"messages\": [\"" + send_msg + "\"]}";

                            // 得到输出流，将POST数据写入流中
                            try(OutputStream os = conn.getOutputStream()){
                                byte[] input = jsonInputString.getBytes("utf-8");
                                os.write(input, 0, input.length);
                            }

                            // 获取响应码
                            int responseCode = conn.getResponseCode();
                            Log.d("MainActivity","Response Code : " + responseCode);

                            // 接收响应流，并转换为字符串
                            try(BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf-8"))){
                                StringBuilder response = new StringBuilder();
                                String responseLine = null;
                                while ((responseLine = br.readLine()) != null) {
                                    response.append(responseLine.trim());
                                }
                                Log.d("MainActivity","Response Body : " + response.toString());

                                // 解析JSON字符串
                                JSONObject jsonObj = new JSONObject(response.toString());
                                String text = jsonObj.getString("text");
                                Boolean reached_end = jsonObj.getBoolean("reached_end");
                                String finish_reason = jsonObj.getString("finish_reason");

                                Log.d("MainActivity","text: " + text);
                                Log.d("MainActivity","reached_end: " + reached_end);
                                Log.d("MainActivity","finish_reason: " + finish_reason);

                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        chatMessages.add(new ChatMessage(text, false));
                                        chatAdapter.notifyItemInserted(chatMessages.size()-1);
                                    }
                                });
                            }

                        } catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });

                thread.start();

            }
        });
        return view;

    }
}

